﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;

namespace SystemsAdmin
{
    public class ExternalApp
    {
        public string PsExecPath { get; set; }

        //Executes a command by calling psexec cmd /c "The command passed"
        // Any quotes in the command will be escaped.
        public string ExecuteCommand(Computer execute_in_comp, string command, string username, string password)
        {
            command = command.Replace("\"", "\"\"");
            if (username != null && username.Trim().Length > 0)
                return RunReturningOutput(PsExecPath, @"\\" + execute_in_comp.IPAddress + " -u " + username + " -p " + password + " cmd /c  \"" + command + "\" ");
            else
                return RunReturningOutput(PsExecPath, @"\\" + execute_in_comp.IPAddress + " cmd /c  \"" + command + "\" ");
        }

        public void StartRemoteDesktop(Computer comp_to_remote)
        {
            string executable = Environment.ExpandEnvironmentVariables(@"%SystemRoot%\system32\mstsc.exe");
            string result = RunReturningOutput(executable, comp_to_remote.GenerateRdpFile());
        }

        private string RunReturningOutput(string path_to_exe, string args)
        {
            var proc = new Process();
            Process p = new Process();
            String s;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.FileName = path_to_exe;
            p.StartInfo.Arguments = args;
            p.Start();
            StreamReader reader = p.StandardOutput;
            StreamReader err_reader = p.StandardError;
            s = reader.ReadToEnd();
            s += "\n" + err_reader.ReadToEnd();
            return s;
        }
    }
}
